"""
机票预订系统主应用
"""
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import uvicorn
from common.redis import RedisManager
from common.postgres import postgres_lifespan
from common.logger import logger
from api.chat import router as chat_router
from fastapi.responses import RedirectResponse

# Redis 管理器
REDIS_URI = "redis://localhost:6379/0?password=123456"
redis_manager = RedisManager(REDIS_URI)
DB_URI = "postgresql://postgres:123456@localhost:5432/llm"


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理：使用推荐的上下文管理器方式管理连接池"""
    # 使用 PostgreSQL 生命周期管理器
    async with postgres_lifespan(
        db_uri=DB_URI, init_start=True, min_size=1, max_size=20
    ) as (pool, checkpointer, store):

        app.state.pool = pool
        app.state.checkpointer = checkpointer
        app.state.store = store

        # 初始化 Redis
        redis = await redis_manager.initialize()
        app.state.redis = redis

        logger.info("✅ Postgres checkpointer&store 和 Redis 初始化完成")

        try:
            yield
        finally:
            # ---- 关闭时 ----
            await redis_manager.close()
            logger.info("🛑 Redis 已关闭")


# 创建FastAPI应用
app = FastAPI(
    title="机票预订系统", 
    lifespan=lifespan
    )

# 设置静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 添加根路由重定向到主页
@app.get("/")
async def root_redirect():
    """将根路径重定向到主页"""
    return RedirectResponse(url="/home")

# 包含API路由
app.include_router(chat_router)


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)